package cn.lijiajia3515.cairo.auth.framework.security.web.authentication;

import cn.lijiajia3515.cairo.auth.domain.mongo.AccountMongo;
import cn.lijiajia3515.cairo.auth.domain.mongo.AuthMongoConstants;
import cn.lijiajia3515.cairo.auth.framework.security.CairoAuthAccount;
import org.springframework.context.event.EventListener;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class UpdateLastLoginTimeAccountListener {
	private final MongoTemplate mongoTemplate;

	public UpdateLastLoginTimeAccountListener(MongoTemplate mongoTemplate) {
		this.mongoTemplate = mongoTemplate;
	}


	@EventListener(AuthenticationSuccessEvent.class)
	public void success(AuthenticationSuccessEvent event) {
		Authentication authentication = event.getAuthentication();
		if (authentication.getPrincipal() instanceof CairoAuthAccount) {
			CairoAuthAccount authUser = (CairoAuthAccount) authentication.getPrincipal();
			LocalDateTime now = LocalDateTime.now();
			Query query = Query.query(Criteria.where(AccountMongo.FIELD.ID).is(authUser.getId()));
			Update update = Update.update(AccountMongo.FIELD.LAST_LOGIN_AT, now);
			mongoTemplate.updateFirst(query, update, AccountMongo.class, AuthMongoConstants.Collection.ACCOUNT);
		}
	}

}
